<template>
  <div class="search-suggestion">
    <!-- :title="key" -->
    <van-cell
      v-for="key in suggestions"
      :key="key"
      icon="search"
      @click="$emit('searchT', key)"
    >
      <!-- 在v-html中可以执行一个函数; -->
      <div slot="title" v-html="heighLight(key)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from "@/api/search.js";

export default {
  name: "SearchSuggestion",
  data() {
    return {
      suggestions: [],
    };
  },
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  watch: {
    searchText: {
      //当search发生改变的时候 触发请求
      handler(val) {
        console.log(val);
        this.loadSearchSuggestions(val);
      },
      immediate: true, //拿到第一次的内容
    },
  },
  methods: {
    async loadSearchSuggestions(q) {
      try {
        const {
          data: {
            data: { options },
          },
        } = await getSearchSuggestions(q);
        this.suggestions = options;
        // console.log(options);
      } catch (err) {
        console.log("联想建议请求失败,请稍后再试!");
      }
    },
    heighLight(text) {
      let reg = new RegExp(this.searchText, "ig");
      let htmlStr = `<span style="color:#3296fa;">${this.searchText}</span>`;
      // 注意:一定要有返回值;
      return text.replace(reg, htmlStr);
    },
  },
};
</script>
<style scoped lang="less">
.search-suggestion {
  /deep/.van-icon {
    color: #999 !important;
  }
}
</style>
